<template>
    <div class="components_edit_modal">
        <el-dialog :title="edited?'院校修改':'院校添加'" :visible.sync="state"  :show-close="true" :close-on-click-modal="false">
            <el-form :model="schoolParams"   :rules="rules" ref="schoolParams" label-position="right">
                        <el-form-item label="院校名称"  prop="name">
                                <el-input v-model.trim="schoolParams.name" placeholder="请输入院校名称"></el-input>
                             </el-form-item>
                            <el-form-item label="院校性质"  prop="type">
                                <el-select v-model="schoolParams.type" placeholder="请选择院校性质" value-key="value">
                                    <el-option
                                        v-for="item in schoolType" :key="item.id"
                                        :label="item.text"
                                        :value="item.id">
                                    </el-option>
                                    </el-select>
                             </el-form-item>
                            <el-form-item label="所在省份"  prop="province">
                                <el-select v-model="schoolParams.province" @change="changeProvince" placeholder="请选择所在省份" value-key="value">
                                    <el-option
                                        v-for="item in provinceList" :key="item.id"
                                        :label="item.fullName"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                             </el-form-item>
                            <el-form-item label="所在城市" prop="city">
                                <el-select v-model="schoolParams.city" placeholder="请选择所在城市" value-key="value">
                                    <el-option
                                        v-for="item in cityList" :key="item.id"
                                        :label="item.fullName"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="所属区域" >
                              <el-input prop="area"
                                        placeholder="请选择所属机构"
                                        @focus="showTree"
                                        v-model="schoolParams.areaName"></el-input>
                                    <div class="zTree_box model_ct">
                                        <div id="thrTree1" v-show="isZTree">
                                          <!-- show-checkbox-->
                                            <!-- <el-tree
                                            :data="zTreeList"
                                            default-expand-all
                                            check-strictly
                                            show-checkbox
                                            ref="tree"
                                            node-key="id"
                                            :props="defaultProps"
                                            :default-checked-keys="[schoolParams.area]"
                                            @check-change="handleCheckChange">
                                            </el-tree> -->
                                            <ul class="ztree orgTree1" id="orgTree1"></ul>
                                        </div>
                                    </div>

                            </el-form-item>



                            <el-form-item label="校区主管" prop="schoolManagerId" class="lineblock">
                                <el-select v-model="schoolParams.schoolManagerId" filterable multiple placeholder="请选择" value-key="value" size="mini">
                                    <el-option
                                         v-for="item in schoolLeaderList" :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="备注" prop="remark" class="lineblock textareaBox">
                              <el-input type="textarea" v-model="schoolParams.remark" placeholder="请输入备注"></el-input>
                            </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" @click="addSchool('schoolParams')">确 定</el-button>
                <el-button @click="state = false" size="small">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {enums} from '@/constant'
    /*树形插件----开始*/
    // import vbootstrapStyle from '../../../../../'
    import vbootstrapStyle from '../../../../../static/css/bootstrapStyle.css'
    import vZtreeCore from '../../../../../static/js/jquery.ztree.core.js'
    import vZtreeExcheck from '../../../../../static/js/jquery.ztree.excheck.js'
    export default {
        data() {

            return {
                 edited:false,
                 state: false,
                 rules: {
                    name: [
                        { required: true, message: '院校名称不能为空', trigger: 'blur'},
                        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
                    ],
                    type: [
                        { required: true, message: '请选择院校性质', trigger: 'change',type:'number'},
                    ],
                    area: [
                        { required: true, message: '院校机构不能为空', trigger: 'blur' },
                    ],
                    province: [
                        { required: true, message: '省份不能为空', trigger: 'change',type:'number'},
                    ],
                    city: [
                        { required: true, message: '城市不能为空', trigger: 'change',type:'number'},
                    ],
                    schoolManagerId: [
                        { required: true, message: '请选择校区主管'},
                    ],
                 },
                schoolParams: {
                    id:null,
                    name:null,
                    type:null,
                    area:null,
                    areaName:null,
                    officeId:null,
                    province:null,
                    city:null,
                    schoolManagerId:[],
                    remark:null
                },
                 // 专业性质枚举
                schoolType: enums.SCHOOL_TYPE,
                //负责人
                schoolLeaderList:[],
                //tree
                isZTree:false,
                zTreeList:[],
                managermentCenterName:null, //选中的tree中的值
                defaultProps: {
                    children: 'child',
                    label: 'name'
                },
                provinceList:[],
                cityList:[]
            }
        },
        created() {
            //获取校区主管

        },
        mounted() {},
        methods: {
            // 打开模态框
            showDialog(){
                let self = this;
                if(this.$refs['schoolParams']!==undefined){
                    this.$refs['schoolParams'].resetFields();
                    if($.fn.zTree.getZTreeObj("thrTree1")){
                        $.fn.zTree.getZTreeObj("thrTree1").checkAllNodes(false);
                    }
                }
                this.state = true;
                this.schoolManagerId = [];
                this.init();
                this.getSchoolLeaderList();
                this.getTree((response)=>{
                    self.zTreeList = response;
                });
                this.getProvinceList();
                this.zTreeEdit();
                console.log(this.schoolParams);
            },
            //获取编辑信息
            editSchoolDetail(val){
                if(this.$refs['schoolParams']!==undefined){
                    this.$refs['schoolParams'].resetFields();
                    if($.fn.zTree.getZTreeObj("thrTree1")){
                        $.fn.zTree.getZTreeObj("thrTree1").checkAllNodes(false);
                    }
                }
                let vm = this;
                vm.edited = true;
                vm.isZTree = false;
                vm.state = true;
                for(let key in this.schoolParams){
                  this.schoolParams[key] = null;
                }
                this.cityList = [];
                this.getSchoolLeaderList();
                this.schoolParams.areaName = val.officeName;
                vm.schoolParams.schoolManagerId = [];

                vm.axios.get(api.getSchoolDetail+val.id).then((response) => {
                if (response.data.success) {
                    let schoolDetail = response.data.data;

                    for(let key in schoolDetail){
                      vm.schoolParams[key] = schoolDetail[key];
                    }

                    vm.schoolParams['area'] =  schoolDetail.officeName;
                    vm.schoolParams['schoolManagerId'] = vm.getSchoolManagerId(schoolDetail);
                    if(schoolDetail.province){
                        vm.getCitys(schoolDetail.province);
                    }
                } else {
                    vm.$message.error(response.data.msg);
                }
                })
                this.getProvinceList();
                vm.zTreeEdit();

            },

            //初始化控件
            init(){
                this.isZTree = false;
                this.edited = false;
                for(let key in this.schoolParams){
                  this.schoolParams[key] = null;
                  if(key == 'schoolManagerId'){
                    this.schoolParams[key] = [];
                  }
                }
                this.cityList = [];
            },
            // 获取学校数据
            getSchoolList() {
                let vm = this;
                vm.axios.get(api.getSchoolList).then((response) => {
                    if (response.data.success) {
                        vm.schoolList = JSON.parse(JSON.stringify(response.data.data));
                    } else {
                        vm.$message.error(response.data.msg);
                    }
                })
            },
             // 获取二级院系数据
            getSecondSchoolList(schoolId) {
                let vm = this;
                vm.axios.get(api.getSecondSchoolList,{
                    params: {
                        schoolId: schoolId
                    }
                }).then((response) => {
                    if (response.data.success) {
                        this.secondSchoolList = JSON.parse(JSON.stringify(response.data.data));
                    } else {
                        vm.$message.error(response.data.msg);
                    }
                })
            },

            // 新建学校
            addSchool(schoolParams) {
                let vm = this;
                this.$refs['schoolParams'].validate((valid) => {
                    if (valid) {
                        let schoolParamsN = {
                            name:vm.schoolParams.name,
                            type:vm.schoolParams.type,
                            officeId:vm.schoolParams.officeId,
                            province:vm.schoolParams.province,
                            city:vm.schoolParams.city,
                            schoolManagerId:vm.getPassParams(),
                            remark:vm.schoolParams.remark
                        }
                        let url =api.saveSchool;
                        if(vm.edited){
                            url = api.editSchool;
                            schoolParamsN.id = vm.schoolParams.id;
                        }
                        vm.axios.post(url,schoolParamsN)
                        .then((response) => {
                            if (response.data.success) {
                                vm.$message({
                                    type: 'success',
                                    message: response.data.msg,
                                });
                                vm.$emit('refreshList');
                                vm.state = false;
                            } else {
                                vm.$message.error(response.data.msg);
                            }
                        })
                    } else {
                        return false;
                    }
                });

            },
            //获取全部的用户列表
            getSchoolLeaderList(){
                let vm = this;
                vm.axios.get(api.queryAllUserList
                ).then((response) => {
                    if (response.data.success) {
                        vm.schoolLeaderList = JSON.parse(JSON.stringify(response.data.data));
                    } else {
                        vm.$message.error(response.data.msg);
                    }
                });
            },
            showTree(){
                 this.isZTree = !this.isZTree;
            },
             // 树结构点击
            handleCheckChange(data, checked, indeterminate) {
              this.$refs.tree.setCheckedKeys([ this.schoolParams.officeId ]);
                if(checked == true && indeterminate == false){
                    console.log(data);
                this.schoolParams.areaName = data.name;
                this.schoolParams.area = data.id;
                this.schoolParams.officeId = data.id;
                this.isZTree = false;
                }
            },
            // 获得树形列表
            getTree(success) {
                let self = this;
                self.axios({
                    method: "get",
                    url: api.officesTreeUrl
                })
                .then(function(response) {
                    if(response.data.success){
                        success(response.data.data);
                   }else{
                       self.$message({
                        duration: 1000,
                        message: response.data.msg,
                        center: true,
                        type: "error"
                        });
                    }
                })
            },
            getPassParams(){
                let schoolManagerId = this.schoolParams.schoolManagerId.join();
                return schoolManagerId;
            },
            getSchoolManagerId(schoolDetail){
                let idsN = [];
                let ids = schoolDetail.schoolManagerId.split(",");
                ids.map((item)=>{
                    idsN.push(parseInt(item));
                })
                console.log(idsN);
                return idsN;
            },
            //获取省
            getProvinceList(){
                let self = this;
                self.axios.get(api.area.province)
                .then((response) => {
                    self.provinceList = JSON.parse(JSON.stringify(response.data.data));
                })
            },
            //获取市
            changeProvince(provinceId){
                let self = this;
                self.axios.get(api.area.city+provinceId)
                .then((response) => {
                    self.schoolParams.city = null;
                    self.cityList = JSON.parse(JSON.stringify(response.data.data.child));
                })
            },
            getCitys(provinceId){
                let self = this;
                self.axios.get(api.area.city+provinceId)
                .then((response) => {
                    console.log(response.data.data);
                    self.cityList = JSON.parse(JSON.stringify(response.data.data.child));
                })
            },
            //  返回对象
            getName(json, id) {
                if(id == null){
                    let passParams = {
                        name:""
                    };
                    return passParams;
                }
                for (var i = 0; i < json.length; i++) {
                    var model = json[i];
                    if (model.id == id) {
                        return model;
                    }
                    if (model.child != null && model.child.length > 0) {
                        this.getName(model.child, id);
                        // var name = this.getName(model.child, id);
                        // if (name != null) {
                        //     return name;
                        // }
                    }
                }
                return null;
            },
            zTreeEdit(){
                let self = this;
                var setting = {
                    view: {
                        dblClickExpand: false
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    callback:{
                      //点击事件
                      onClick: zTreeOnClick,
                      onCheck: zTreeCheck,
                    }
                };

                self.axios({
                    method: "get",
                    url: self.axios.defaults.baseURL + "/offices/tree"
                })
                .then(function(response) {
                    var zNodes = [];
                    zNodes = response.data.data;
                        // var parentItem = self.getName(zNodes,self.schoolParams.officeId);
                        // self.schoolParams.areaName = parentItem.name;
                        // console.log(self.schoolParams.areaName);
                    // 初始化树形结构
                    $.fn.zTree.init($("#orgTree1"), setting, zNodes);
                })

                function zTreeOnClick(e, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                    var node = treeObj.getNodeByTId(treeNode.tId);
                    console.log(node);
                    self.schoolParams.areaName = node.name;
                    self.schoolParams.area = node.id;
                    self.schoolParams.officeId = node.id;
                    self.hideMenu();
                };
                // 定义勾选事件
                function zTreeCheck(event, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj(treeId);
                    var node = treeObj.getNodeByTId(treeNode.tId);
                    self.schoolParams.officeId = node.id;
                    self.schoolParams.areaName = node.name;
                    self.schoolParams.area = node.id;
                    self.isZTree = !self.isZTree;
                };
            },
            onBodyDown(event) {
                let self = this;
                if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || event.target.id == "thrTree1" || $(event.target).parents("#thrTree1").length>0)) {
                    self.hideMenu();
                }
            },
            showMenu() {
                let self = this;
                var cityObj = $("#thrTree1");
                var cityOffset = $("#thrTree1").offset();
                $("#thrTree1").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");

                $("body").bind("mousedown", self.onBodyDown);
                return false;
            },
            hideMenu() {
                let self = this;
                $("#thrTree1").fadeOut("fast");
                $("body").unbind("mousedown", self.onBodyDown);
                return false;
            },
            //显示树结构
            showTree(){
                this.isZTree = !this.isZTree;
            },

        },
        components: {}
    };
</script>
<style scoped>
    .model_ct{width: 100%; position: absolute; top: 33px ;left:0; background: #FFF; z-index: 10; }
    #thrTree1{ padding: 10px; max-height:200px; overflow-y: auto; border-radius: 4px; border: 1px solid #dedede;}
    .orgEdit .el-select{width: 100%;}
</style>
